﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace HY.Common
{
    public class PostHelper
    {
        ///<summary>
        ///采用https协议访问网络(Post方式)
        ///</summary>
        ///<param name="URL">url地址</param>
        ///<param name="paras">发送的数据</param>
        ///<returns></returns>
        public static string PostHttpByKeyValue(string url, Dictionary<string, string> paras)
        {
            StringBuilder querystring = new StringBuilder();
            foreach (var para in paras)
            {
                querystring.Append(string.Format("&{0}={1}", para.Key, para.Value));
            }
            if (querystring.Length > 0)
                querystring.Remove(0, 1);

            string contentType = "application/x-www-form-urlencoded";
            return PostHttp(url, querystring.ToString(), Encoding.UTF8, contentType);
        }
        ///<summary>
        ///采用https协议访问网络(Post方式，参数传送方式：Raw)(资源变更时使用)
        ///</summary>
        ///<param name="URL">url地址</param>
        ///<param name="querystring">发送的数据(示例："{\"PROVINCE\":\"125\",\"STAFF_ID\":\"-1\",\"DATAS\":[{\"GID\":\"410102050000001123042898\",\"NAME\":\"某局站1\",\"X\":\"134.123451\",\"Y\":\"36.123451\"},{\"GID\":\"410102050000001123042899\",\"NAME\":\"某局站2\",\"X\":\"134.678911\",\"Y\":\"36.689721\"}]}")</param>
        ///<returns></returns>
        public static string PostHttpByRaw(string url, string querystring)
        {
            string contentType = "application/json";
            return PostHttp(url, querystring, Encoding.UTF8, contentType);
        }
        ///<summary>
        ///采用https协议访问网络(Post方式)
        ///</summary>
        ///<param name="URL">url地址</param>
        ///<param name="querystring">发送的参数</param>
        ///<param name="encoding">编码格式</param>
        ///<param name="contentType">request.ContentType</param>
        ///<returns></returns>
        private static string PostHttp(string url, string querystring, Encoding encoding, string contentType)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "post";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = contentType;
            byte[] buffer = encoding.GetBytes(querystring);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader sr = new StreamReader(response.GetResponseStream(), encoding))
            {
                return sr.ReadToEnd();
            }
        }
    }
}
